'use client'

import { useState, useEffect } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { DatePickerWithRange } from '@/components/DatePickerWithRange'
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { BarChart3, Table as TableIcon, Download, ArrowDown, ArrowUp } from 'lucide-react'
import { toast } from 'sonner'
import type { DateRange } from 'react-day-picker'
import { format } from 'date-fns'
import { TooltipProps } from 'recharts'
import { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'

type TimeRange = 'today' | 'week' | 'month' | 'custom'
type MetricType = 'tangzhuang' | 'movie' | 'hanfu'
type ViewType = 'chart' | 'table'
type ChartType = { title: string; id: string; type: 'image' | 'share' }

interface MetricCard {
  id: string
  title: string
  value: number
  unit?: string
  type: 'image' | 'share'
  category: MetricType | 'total'
  change?: {
    day: number
    week: number
  }
}

interface BaseGenderData {
  name: string;
  value: number;
  count: number;
}

interface GenderDataItem extends BaseGenderData {}

interface GenderChartData extends BaseGenderData {}

interface ChartDataItem extends BaseGenderData {}

const TIME_RANGES: { value: TimeRange; label: string }[] = [
  { value: 'today', label: '本日' },
  { value: 'week', label: '本周' },
  { value: 'month', label: '本月' },
  { value: 'custom', label: '自定义' },
]

const METRICS = {
  tangzhuang: '唐装写真',
  movie: '热门电视剧',
  hanfu: '制式汉服'
} as const

const COLORS = ['#0088FE', '#00C49F']

const CHARTS: ChartType[] = [
  { title: '生图次数占比', id: 'count', type: 'image' },
  { title: '生图人数占比', id: 'users', type: 'image' },
  { title: '分享数占比', id: 'shares', type: 'share' }
]

// 格式化数字的辅助函数
const formatNumber = (num: number) => {
  return new Intl.NumberFormat('zh-CN').format(num)
}

// 渲染增长率的组件
const GrowthRate = ({ 
  value, 
  label 
}: { 
  value: number | null | undefined
  label: string
}) => {
  if (value === null || value === undefined) {
    return (
      <div className="flex items-center text-sm">
        <span className="text-gray-500 mr-2">{label}</span>
        <span className="text-gray-500">--</span>
      </div>
    )
  }

  const numericValue = Number(value)
  if (isNaN(numericValue)) {
    return (
      <div className="flex items-center text-sm">
        <span className="text-gray-500 mr-2">{label}</span>
        <span className="text-gray-500">--</span>
      </div>
    )
  }

  return (
    <div className="flex items-center text-sm">
      <span className="text-gray-500 mr-2">{label}</span>
      <span className={`flex items-center ${numericValue > 0 ? 'text-green-500' : 'text-red-500'}`}>
        {numericValue > 0 ? <ArrowUp className="w-3 h-3 mr-1" /> : <ArrowDown className="w-3 h-3 mr-1" />}
        {numericValue > 0 ? '+' : ''}{numericValue.toFixed(2)}%
      </span>
    </div>
  )
}

// Add interfaces for API response types
interface OverviewData {
  totalGenerationCount: {
    value: number
    dayOnDay: number
    weekOnWeek: number
  }
  totalShares: {
    value: number
    dayOnDay: number
    weekOnWeek: number
  }
  avgProcessTime: {
    value: number
    dayOnDay: number
    weekOnWeek: number
  }
  totalFailCount: {
    value: number
    dayOnDay: number
    weekOnWeek: number
  }
}

interface GenderData {
  [key: string]: {
    generation: Array<BaseGenderData>
    users: Array<BaseGenderData>
    shares: Array<BaseGenderData>
  }
}

// 添加下载按钮组件
const DownloadButton = ({ timeRange, dateRange, selectedStyles }: { 
  timeRange: string, 
  dateRange: DateRange | undefined,
  selectedStyles: string[]
}) => {
  const handleDownload = () => {
    // 构建查询参数
    const params = new URLSearchParams();
    params.append('timeRange', timeRange);
    
    if (dateRange?.from) {
      params.append('startDate', format(dateRange.from, 'yyyy-MM-dd'));
    }
    if (dateRange?.to) {
      params.append('endDate', format(dateRange.to, 'yyyy-MM-dd'));
    }
    
    selectedStyles.forEach(style => {
      params.append('styleIds[]', style);
    });

    // 发起下载请求
    const url = `/api/makeup-analysis/export?${params.toString()}`;
    window.open(url, '_blank');
  };

  return (
    <Button
      variant="outline"
      size="sm"
      onClick={handleDownload}
      className="ml-auto"
    >
      导出数据
    </Button>
  );
};

export default function MakeupAnalysisPage() {
  const [timeRange, setTimeRange] = useState<TimeRange>('today')
  const [dateRange, setDateRange] = useState<DateRange | undefined>()
  const [selectedMetrics, setSelectedMetrics] = useState<MetricType[]>([])
  const [timeDescription, setTimeDescription] = useState<string>('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [overviewData, setOverviewData] = useState<OverviewData | null>(null)
  const [genderData, setGenderData] = useState<GenderData | null>(null)
  const [isMetricsLoading, setIsMetricsLoading] = useState(false)
  const [isChartLoading, setIsChartLoading] = useState(false)

  // Fetch data function
  const fetchData = async () => {
    try {
      // 只在数据真正开始加载时显示加载状态
      if (!overviewData) setIsMetricsLoading(true)
      if (!genderData) {
        setIsChartLoading(true)
      }

      // Prepare query parameters
      const params = new URLSearchParams()
      if (timeRange === 'custom' && dateRange?.from && dateRange?.to) {
        // params.append('startDate', dateRange.from.toISOString().split('T')[0])
        // params.append('endDate', dateRange.to.toISOString().split('T')[0])
        params.append('startDate', format(dateRange.from, 'yyyy-MM-dd'))
        params.append('endDate', format(dateRange.to, 'yyyy-MM-dd'))
      } else {
        params.append('timeRange', timeRange)
      }
      
      // 总是添加所有可用的 styleIds
      if (selectedMetrics.length === 0) {
        // 如果没有选择任何模块，默认获取所有模块数据
        params.append('styleIds[]', '1') // tangzhuang
        params.append('styleIds[]', '4') // movie
        params.append('styleIds[]', '6') // hanfu
      } else {
        selectedMetrics.forEach(metric => {
          const styleId = metric === 'tangzhuang' ? '1' : 
                         metric === 'movie' ? '4' : 
                         metric === 'hanfu' ? '6' : null
          if (styleId) {
            params.append('styleIds[]', styleId)
          }
        })
      }

      // 并行请求数据
      const [overviewResponse, genderResponse] = await Promise.all([
        fetch(`/api/makeup-analysis/overview?${params}`),
        fetch(`/api/makeup-analysis/gender?${params}`)
      ])

      const [overviewResult, genderResult] = await Promise.all([
        overviewResponse.json(),
        genderResponse.json()
      ])

      if (!overviewResult.success) {
        throw new Error(overviewResult.message || '获取总览数据失败')
      }
      if (!genderResult.success) {
        throw new Error(genderResult.message || '获取性别维度数据失败')
      }

      // 添加数据检查日志
      console.log('Gender data received:', genderResult.data)

      setOverviewData(overviewResult.data)
      setGenderData(genderResult.data)
    } catch (err) {
      console.error('Error fetching data:', err)
      setError(err instanceof Error ? err.message : '数据获取失败')
      toast.error('数据获取失败，请稍后重试')
    } finally {
      setIsMetricsLoading(false)
      setIsChartLoading(false)
    }
  }

  // Fetch data when time range or selected metrics change
  useEffect(() => {
    const debounceTimeout = setTimeout(() => {
      fetchData()
    }, 300) // 300ms 的防抖延迟

    return () => clearTimeout(debounceTimeout)
  }, [timeRange, dateRange, selectedMetrics])

  // Convert API data to metrics cards
  const allMetrics: MetricCard[] = [
    {
      id: 'total-image',
      title: '生图总次数',
      value: overviewData?.totalGenerationCount.value || 0,
      type: 'image',
      category: 'total',
      change: overviewData ? {
        day: overviewData.totalGenerationCount.dayOnDay,
        week: overviewData.totalGenerationCount.weekOnWeek
      } : undefined
    },
    {
      id: 'total-share',
      title: '分享总次数',
      value: overviewData?.totalShares.value || 0,
      type: 'share',
      category: 'total',
      change: overviewData ? {
        day: overviewData.totalShares.dayOnDay,
        week: overviewData.totalShares.weekOnWeek
      } : undefined
    },
    {
      id: 'avg-time',
      title: '平均生图时长',
      value: overviewData?.avgProcessTime.value || 0,
      unit: '秒',
      type: 'image',
      category: 'total',
      change: overviewData ? {
        day: overviewData.avgProcessTime.dayOnDay,
        week: overviewData.avgProcessTime.weekOnWeek
      } : undefined
    },
    {
      id: 'fail-count',
      title: '生图失败总次数',
      value: overviewData?.totalFailCount.value || 0,
      type: 'image',
      category: 'total',
      change: overviewData ? {
        day: overviewData.totalFailCount.dayOnDay,
        week: overviewData.totalFailCount.weekOnWeek
      } : undefined
    }
  ]

  // 根据选中的指标筛选显示的数据
  const filteredMetrics = allMetrics.filter(metric => 
    metric.category === 'total' || selectedMetrics.includes(metric.category as MetricType)
  )

  // 表格数据
  const tableData = selectedMetrics.flatMap(metric => {
    const styleData = genderData?.[METRICS[metric]]
    if (!styleData) return []

    return [
      {
        date: timeDescription,
        category: METRICS[metric],
        type: '生图',
        imageCount: styleData.generation.reduce((sum, item) => sum + item.value, 0),
        userCount: styleData.users.reduce((sum, item) => sum + item.value, 0),
        shareCount: styleData.shares.reduce((sum, item) => sum + item.value, 0),
        failCount: overviewData?.totalFailCount.value || 0
      }
    ]
  })

  // 修改表格数据处理逻辑
  const getTableData = () => {
    if (!genderData || !overviewData) return []

    // 如果没有选择任何模块，显示所有模块数据
    const metricsToShow = selectedMetrics.length === 0 ? 
      Object.keys(METRICS) as MetricType[] : 
      selectedMetrics

    return metricsToShow.flatMap(metric => {
      const styleData = genderData[METRICS[metric]]
      if (!styleData) return []

      // 计算总数时使用 count 属性而不是 value
      const totalGeneration = styleData.generation.reduce((sum, item) => sum + (item.count || 0), 0)
      const totalUsers = styleData.users.reduce((sum, item) => sum + (item.count || 0), 0)
      const totalShares = styleData.shares.reduce((sum, item) => sum + (item.count || 0), 0)
      
      return [{
        date: timeDescription,
        category: METRICS[metric],
        type: '生图',
        imageCount: totalGeneration || 0,
        userCount: totalUsers || 0,
        shareCount: totalShares || 0,
        failCount: overviewData.totalFailCount.value || 0
      }]
    })
  }

  // 修改 getGenderData 函数
  const getGenderData = (chartType: ChartType): GenderDataItem[] => {
    if (!genderData) {
      return []
    }

    // 获取要处理的模块列表
    const stylesToProcess = selectedMetrics.length === 0 ? 
      ['tangzhuang', 'movie', 'hanfu'] : 
      selectedMetrics

    const moduleMapping: Record<string, string> = {
      tangzhuang: '唐装写真',
      movie: '热门电视剧',
      hanfu: '制式汉服'
    }

    // 初始化男女数据结构
    let maleData = { name: '男', value: 0, count: 0 }
    let femaleData = { name: '女', value: 0, count: 0 }

    // 合并所有选中模块的数据
    stylesToProcess.forEach(styleKey => {
      const mappedStyle = moduleMapping[styleKey]
      const styleData = genderData[mappedStyle]
      
      if (!styleData) {
        return
      }

      let data
      switch (chartType.id) {
        case 'count':
          data = styleData.generation
          break
        case 'users':
          data = styleData.users
          break
        case 'shares':
          data = styleData.shares
          break
        default:
          return
      }

      if (!data || data.length === 0) {
        return
      }

      // 累加男女数据
      data.forEach(item => {
        if (item.name === '男') {
          maleData.count += Number(item.count || 0)
          maleData.value += Number(item.value || 0) * (item.count || 0)
        } else if (item.name === '女') {
          femaleData.count += Number(item.count || 0)
          femaleData.value += Number(item.value || 0) * (item.count || 0)
        }
      })
    })

    const totalCount = maleData.count + femaleData.count
    
    if (totalCount === 0) {
      return []
    }

    // 计算加权平均百分比
    return [
      {
        name: '男',
        value: Number(((maleData.count / totalCount) * 100).toFixed(2)),
        count: maleData.count
      },
      {
        name: '女',
        value: Number(((femaleData.count / totalCount) * 100).toFixed(2)),
        count: femaleData.count
      }
    ]
  }

  // 更新时间描述
  const updateTimeDescription = (newTimeRange: TimeRange, customRange?: DateRange) => {
    const today = new Date()
    let description = ''

    switch (newTimeRange) {
      case 'today':
        description = `${today.getFullYear()}年${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'week':
        const weekStart = new Date(today)
        weekStart.setDate(today.getDate() - 6)
        description = `${weekStart.getMonth() + 1}月${weekStart.getDate()}日 至 ${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'month':
        description = `${today.getFullYear()}年${today.getMonth() + 1}月1日 至 ${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'custom':
        if (customRange?.from && customRange?.to) {
          const fromDate = customRange.from.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
          const toDate = customRange.to.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
          description = `${fromDate} 至 ${toDate}`
        }
        break
    }

    setTimeDescription(description)
  }

  // 初始化时设置时间描述
  useEffect(() => {
    updateTimeDescription('today')
  }, [])

  const handleTimeRangeChange = (newTimeRange: TimeRange) => {
    setTimeRange(newTimeRange)
    updateTimeDescription(newTimeRange, dateRange)
  }

  const handleDateRangeChange = (range: DateRange | undefined) => {
    setDateRange(range)
    if (range?.from && range?.to) {
      updateTimeDescription('custom', range)
    }
  }

  function toggleMetric(metric: MetricType) {
    setSelectedMetrics(prev => {
      if (prev.includes(metric)) {
        return prev.filter(m => m !== metric)
      }
      return [...prev, metric]
    })
  }

  // Add loading state to the return JSX
  if (loading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6 px-4 pt-4">
      <div className="flex items-center justify-between">
        <h3 className="text-xl font-semibold">妆造分析</h3>
      </div>

      {/* 筛选条件 */}
      <Card className="p-6 shadow-lg">
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              {Object.entries(METRICS).map(([key, label]) => (
                <Button
                  key={key}
                  variant={selectedMetrics.includes(key as MetricType) ? "default" : "outline"}
                  onClick={() => toggleMetric(key as MetricType)}
                  className="shadow-sm hover:shadow-md transition-all duration-200"
                >
                  {label}
                </Button>
              ))}
            </div>

            <div className="flex items-center gap-4">
              <div className="flex items-center gap-2">
                {TIME_RANGES.map(range => (
                  <Button
                    key={range.value}
                    variant={timeRange === range.value ? "default" : "outline"}
                    onClick={() => handleTimeRangeChange(range.value)}
                    className="shadow-sm hover:shadow-md transition-all duration-200"
                  >
                    {range.label}
                  </Button>
                ))}
              </div>
              {timeRange === 'custom' && (
                <div className="relative">
                  <DatePickerWithRange
                    value={dateRange}
                    onChange={handleDateRangeChange}
                  />
                </div>
              )}
            </div>
          </div>
          {/* 时间范围显示 */}
          <div className="flex items-center pt-4 border-t border-gray-100">
            <div className="text-sm text-gray-500">
              当前数据范围：
              <span className="ml-2 text-gray-900 font-medium">{timeDescription}</span>
            </div>
          </div>
        </div>
      </Card>

      {/* 指标卡片 */}
      <div className="grid grid-cols-4 gap-6">
        {filteredMetrics.map((metric) => (
          <Card 
            key={metric.id} 
            className="p-6 shadow-lg hover:shadow-xl transition-all duration-200"
          >
            <div className="space-y-3">
              <div className="text-sm font-medium text-gray-600">{metric.title}</div>
              <div className="text-3xl font-bold text-gray-900">
                {isMetricsLoading ? (
                  <span className="text-gray-300">--</span>
                ) : (
                  <>{formatNumber(metric.value)}{metric.unit}</>
                )}
              </div>
              {metric.change && !isMetricsLoading && (
                <div className="space-y-2 pt-2">
                  <GrowthRate value={metric.change.day} label="较昨日" />
                  <GrowthRate value={metric.change.week} label="较上周" />
                </div>
              )}
            </div>
          </Card>
        ))}
      </div>

      {/* 饼图展示 */}
      <div className="grid grid-cols-3 gap-6">
        {CHARTS.map((chart) => (
          <Card key={chart.id} className="p-6 shadow-lg hover:shadow-xl transition-all duration-200">
            <h3 className="text-lg font-medium text-gray-900 mb-4">{chart.title}（男女维度）</h3>
            <div className="h-[300px]">
              {isChartLoading ? (
                <div className="flex items-center justify-center h-full">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
                </div>
              ) : (
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={getGenderData(chart)}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      outerRadius={100}
                      fill="#8884d8"
                      dataKey="value"
                      nameKey="name"
                      label={({ name, value, payload }: any) => {
                        return `${name}\n${value.toFixed(2)}%\n(${formatNumber(payload.count)})`;
                      }}
                    >
                      {getGenderData(chart).map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip 
                      formatter={(value: any, name: string, entry: any) => {
                        if (typeof value !== 'number') return ['0%'];
                        return [`${value.toFixed(2)}% (${formatNumber(entry.payload.count || 0)})`];
                      }}
                    />
                    <Legend />
                  </PieChart>
                </ResponsiveContainer>
              )}
            </div>
          </Card>
        ))}
      </div>
    </div>
  )
} 